Home:ALL Converter>Synchronizing IsSelected and SelectedItem in a ListView

Synchronizing IsSelected and SelectedItem in a ListView

Ask Time:2012-06-22T04:15:44         Author:qxn

Json Formatter

I have some images (positions) in a WPF control. Each image correlates to an item in a ListView beneath that control. When the user clicks on a position, I want the corresponding ListViewItem to be selected (and therefore highlighted) in the ListView. Similarly, when the user clicks on a ListViewItem, I want the corresponding position to be selected.

I can accomplish one behavior or the other, but I can't seem to get both working together.

I have a Style that sets the IsSelected property to `true' when a position is selected:

<Style x:Key="PositionItem" TargetType="ListViewItem">
    <Setter Property="IsSelected" Value="False" />
    <Style.Triggers>
        <DataTrigger Value="True">
            <DataTrigger.Binding>
                <MultiBinding Converter="{StaticResource IsCurrentPositionConverter}">
                    <Binding RelativeSource="{RelativeSource Self}" Path="DataContext" />
                    <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type UserControl}}" Path="DataContext.CurrentBackplane.CurrentCard.CurrentPosition" />
                </MultiBinding>
            </DataTrigger.Binding>
            <Setter Property="IsSelected" Value="True" />
        </DataTrigger>
    </Style.Triggers>
</Style>

In my ListView, I set a handler for SelectionChanged:

private void Positions_SelectionChanged(object sender, SelectionChangedEventArgs e) {
    var listView = sender as ListView;
    if (listView == null) return;
    var currentPos = listView.SelectedItem as IGraphicPositionViewModel;
    if (currentPos == null) return;
    if (currentPos != _ViewModel.CurrentBackplane.CurrentCard.CurrentPosition)
        _ViewModel.CurrentBackplane.CurrentCard.CurrentPosition = currentPos;
}

The problem is that the IsSelected property of the ListViewItemdoesn't seem to correlate well with the SelectedItem property of the ListView.

Is there some other property or event I can use to synchronize these properties?

Author:qxn,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/11146049/synchronizing-isselected-and-selecteditem-in-a-listview
yy